#!/usr/bin/env python3
"""
Debug script to trace the exact CLI flow
"""
import sys
import os

# Add the parent directory to the path to allow imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from ui.cli import CLI
from system.lms_system import LMSSystem

def debug_cli_flow():
    """Debug the exact CLI flow"""
    print("=== Debugging CLI Flow ===")
    
    # Initialize system
    system = LMSSystem()
    system.initialize()
    
    print(f"System initialized: {system.is_system_ready()}")
    print(f"Course manager exists: {bool(system.course_manager)}")
    
    if system.course_manager:
        courses = system.course_manager.get_all_courses()
        print(f"Courses found: {len(courses)}")
        for course in courses:
            print(f"  - {course.get_name()} ({course.get_id()})")
    
    # Create CLI
    cli = CLI(system)
    print(f"CLI created successfully")
    
    # Test the exact method that would be called
    print("\n=== Testing display_courses method ===")
    
    # Check if system and course_manager are available (same as in display_courses)
    if not cli.system or not cli.system.course_manager:
        print("ERROR: Course manager unavailable")
        return
    
    courses = cli.system.course_manager.get_all_courses()
    print(f"Courses retrieved: {len(courses)}")
    
    if not courses:
        print("ERROR: No courses found")
        return
    
    # Test each course's methods that are called in display_courses
    for course in courses:
        print(f"\nTesting course: {course.get_name()}")
        try:
            course_id = course.get_id()
            course_name = course.get_name()
            course_desc = course.get_description()
            course_max = course.get_max_students()
            course_current = course.get_current_students()
            teacher_id = course.get_teacher_id()
            
            print(f"  ID: {course_id}")
            print(f"  Name: {course_name}")
            print(f"  Description: {course_desc[:30]}...")
            print(f"  Max students: {course_max}")
            print(f"  Current students: {course_current}")
            print(f"  Teacher ID: {teacher_id}")
            
        except Exception as e:
            print(f"  ERROR with course {course.get_name()}: {e}")
            import traceback
            traceback.print_exc()
    
    print("\n=== All tests passed! ===")

if __name__ == "__main__":
    debug_cli_flow()